package com.bzyd.cloud.exception;

import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.alibaba.fastjson.JSON;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义异常返回页面
 * Created by Xianyue Dang on 2021/5/30
 */
@Component
public class ExceptionHandlerPage implements UrlBlockHandler {

    @Override
    public void blocked(HttpServletRequest request, HttpServletResponse response, BlockException e) throws IOException {
        response.setContentType("application/json;charset=utf-8");
        ResponseData responseData = null;
        //BlockException异常接口，包含Sentinel的五个异常
        if (e instanceof FlowException) {//限流异常
            responseData = new ResponseData(-1, "接口被限流了...");
        } else if (e instanceof DegradeException) {//降级异常
            responseData = new ResponseData(-2, "接口被降级了...");
        } else if (e instanceof ParamFlowException) {//参数限流异常
            responseData = new ResponseData(-3, "某参数被针对了...");
        } else if (e instanceof AuthorityException) {//授权异常
            responseData = new ResponseData(-4, "某来源授权被针对了...");
        } else if (e instanceof SystemBlockException) {//系统负荷异常
            responseData = new ResponseData(-5, "系统超负荷了...");
        }
        response.getWriter().write(JSON.toJSONString(responseData));
    }


}

@Data
@AllArgsConstructor
@NoArgsConstructor
class ResponseData {
    private int code;
    private String message;
}
